package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"log"
)

func main() {
	// 创建一个新的文件系统监视器
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	defer watcher.Close()

	// 监听的目录路径
	directoryPath := "/Users/songhao/goProjects/gobyexample/file/test.txt"

	// 将目录添加到监视器中
	err = watcher.Add(directoryPath)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Watching directory: %s\n", directoryPath)

	// 循环等待文件变化事件
	for {
		select {
		case event, ok := <-watcher.Events:
			if !ok {
				return
			}
			fmt.Printf("Event: %v\n", event)
			if event.Op&fsnotify.Write == fsnotify.Write {
				fmt.Println("Modified file:", event.Name)
			} else if event.Op&fsnotify.Create == fsnotify.Create {
				fmt.Println("Created file:", event.Name)
			} else if event.Op&fsnotify.Remove == fsnotify.Remove {
				fmt.Println("Removed file:", event.Name)
			}
		case err, ok := <-watcher.Errors:
			if !ok {
				return
			}
			log.Println("Error:", err)
		}
	}
}
